package com.fc.mall.controller;

import com.fc.mall.base.object.Result;
import com.fc.mall.dto.*;
import com.fc.mall.exception.InternalServerErrorException;
import com.fc.mall.model.UmsMember;
import com.fc.mall.service.UmsMemberAccountChangeHistoryService;
import com.fc.mall.service.UmsMemberAccountService;
import com.fc.mall.service.UmsMemberService;
import com.fc.mall.sysconfig.dto.SysConfigDto;
import com.fc.mall.sysconfig.service.SysConfigService;
import com.fc.mall.util.Utils;
import com.fc.mall.dto.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import net.sf.json.JSONObject;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Sunny on 2019/5/28.
 */
@RestController
@Api(tags = "UmsMemberController", description = "会员管理")
@RequestMapping("/member")
public class UmsMemberController {

    @Autowired
    private UmsMemberService umsMemberService;

    @Autowired
    private SysConfigService configService;

    @Autowired
    private UmsMemberAccountChangeHistoryService umsMemberAccountChangeHistoryService;

    @Autowired
    private UmsMemberAccountService umsMemberAccountService;

    @Autowired
    private MapperFacade mapperFacade;

    @ApiOperation("获取会员列表")
    @GetMapping("list")
    public CommonResult list(@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                             UmsMemberQueryParam queryParam) {
        List<UmsMemberFull> memberList = umsMemberService.getFullMemberList(queryParam, pageNum, pageSize);
        return new CommonResult().pageSuccess(memberList);
    }

    @ApiOperation("手动升级会员")
    @PutMapping("upgrade")
    public Result upgradeMemberLevel(@RequestBody UmsMember umsMember) {
        umsMemberService.upgradeMemberLevel(umsMember);
        return Result.success();
    }

    @DeleteMapping("{memberId}")
    public Result delMember(@PathVariable(name = "memberId") Long memberId) {
        return Result.success(umsMemberService.delMember(memberId));
    }

    @ApiOperation("获取会员详细信息、银行信息、账户信息")
    @GetMapping("{memberId}/information")
    public Result getMemberInformation(@PathVariable(name = "memberId") Long memberId) {

        return Result.success(umsMemberService.getUmsMemberAndAccountAndBankInfo(memberId));
    }

    @ApiOperation("获取会员关系链 API")
    @GetMapping("{memberId}/relation")
    public Result getMemberRelation(@PathVariable(name = "memberId") Long memberId) {
        JSONObject json = new JSONObject();
        List<UmsMemberFull> memberList = umsMemberService.getMemberRelation(memberId);
        SysConfigDto config = configService.queryByCode("buyer_self_commission");
        boolean buyerSelfCommission = false;
        if (null != config) {
            buyerSelfCommission = config.getValue().equals("1");
        }
        json.put("memberList", memberList);
        json.put("isBuyerSelfCommission", buyerSelfCommission);
        return Result.success(json);
    }

    @ApiOperation("获取会员佣金")
    @GetMapping("{memberId}/commission")
    public CommonResult getMemberCommissionList(@PathVariable Long memberId,
                                                UmsMemberCommissionParam umsMemberCommissionParam,
                                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        umsMemberCommissionParam.setMemberId(memberId);
        return new CommonResult().pageSuccess(umsMemberService.getMemberCommissionList(umsMemberCommissionParam, pageNum, pageSize));
    }


    @GetMapping("{memberId}/bank")
    public Result getMemberBankInfo(@PathVariable Long memberId) {
        return Result.success(umsMemberService.getMemberBank(memberId));
    }


    @GetMapping("{memberId}/income/static")
    public Result getMemberIncomeStatic(@PathVariable Long memberId) {
        return Result.success(umsMemberService.getMemberIncomeStatic(memberId));
    }

    @ApiOperation("粉丝列表")
    @GetMapping("{memberId}/queryFansList")
    public CommonResult getMemberAllFans(@PathVariable Long memberId, UmsMemberFansQueryParam param) {
        List<UmsMemberFull> fansList = umsMemberService.queryFansList(memberId,param);
        return new CommonResult().pageSuccess(fansList);
    }

    @ApiOperation("粉丝数量")
    @GetMapping("{memberId}/countFans")
    public Result countMemberFans(@PathVariable Long memberId) {
        UmsMemberFansCount fansCount= umsMemberService.countFans(memberId);
        return Result.success(fansCount);
    }

    @ApiOperation("会员余额变动历史")
    @GetMapping("account/change")
    public CommonResult accountChangeList(UmsMemberAccountChangeHistoryParm parm,
                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        return new CommonResult().pageSuccess(umsMemberAccountChangeHistoryService.queryList(parm,pageSize,pageNum));
    }

    @ApiOperation("调整会员余额")
    @PutMapping("update/account")
    public Result updataAccount(UmsMemberAccountParam param) {
        umsMemberAccountService.updataAccount(param);
        return Result.success();
    }

    @ApiOperation("获取会员佣金不同状态数量、金额")
    @GetMapping("{memberId}/count/status")
    public Result getCommissionStatusCount(@PathVariable Long memberId) {
        return Result.success(umsMemberService.getCommissionStatusCount(memberId));
    }

    @ApiOperation("增加代理的到期时间")
    @PutMapping("add/expired")
    public Result addExpireDate(@RequestBody UmsMemberAddExpireDateParam param){
        umsMemberService.addExpireDate(param);
        return Result.success();
    }

    @ApiOperation("会员佣金导出")
    @GetMapping("exportxls")
    public void exportXls(UmsMemberCommissionParam umsMemberCommissionParam, HttpServletResponse response, Principal principal){
        List<UmsMemberCommission> commissionList = umsMemberService.getMemberCommissionList(umsMemberCommissionParam,1,1000);
        List<UmsMemberCommissionExcel> commissionExcelList = commissionList.stream().map(commission-> {
            UmsMemberCommissionExcel commissionExcel = mapperFacade.map(commission, UmsMemberCommissionExcel.class);
            commissionExcel.setOrderSn(commission.getOrderSn());
            commissionExcel.setCreateTime(commission.getCreateTime());
            commissionExcel.setAmount((float)commission.getAmount()/100);
            commissionExcel.setCommissionType(commission.getCommissionType());
            commissionExcel.setNickname(Utils.urlDecoderTransfer(commission.getNickname()));
            commissionExcel.setRate(commission.getRate()+"%");
            commissionExcel.setReceiveTime(commission.getReceiveTime());
            commissionExcel.setStatus(commission.getStatus());
            return commissionExcel;
        }).collect(Collectors.toList());
        response.setHeader("Content-disposition", "attachment; filename=commission.xls");
        response.setHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        try {
            String  username = principal.getName();
            ExcelExportUtil.exportExcel(new ExportParams("佣金列表", "生成人:" + username, "佣金信息"),
                    UmsMemberCommissionExcel.class, commissionExcelList).write(response.getOutputStream());
        } catch (IOException e) {
            throw new InternalServerErrorException("生成报表失败");
        }
    }
}
